﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Google.GData.Client;
using Google.GData.YouTube;
using System.Text;
using System.Threading;
using System.Globalization;
using Resources;
using Google.GData.Photos;

public partial class PageWithPanels : System.Web.UI.Page
{
    public string TrendWord { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {

        foreach (string key in Request.QueryString)
        {
            switch (key.ToLower())
            {
                case "trendex": this.TrendWord = Request.QueryString[key]; break;
            }
        }
        if (!string.IsNullOrEmpty(this.TrendWord))
        {
            bool PageAllowed = GoogleHelper.CheckKeyWordAllowed(this.TrendWord);
            if (!PageAllowed)
            {
                Response.Redirect("default.aspx");
                Response.Write("this query is not allowed on this page");
            }
        }


        if (!IsPostBack)
        {



            if (string.IsNullOrEmpty(this.TrendWord) || this.TrendWord.ToLower().Contains("buzzminute.com"))
            {
                this.TrendWord = "Breaking News";
            }
            //show news from google        
            GoogleNewsDataSource.DataFile = string.Format(GoogleHelper.GoogleNewsFeedUrl, TrendWord);
            GoogleNewsListView.DataSourceID = GoogleNewsDataSource.UniqueID;
            GoogleNewsListView.DataBind();

            //show blogsearch
            BlogSearchDataSource.DataFile = string.Format(GoogleHelper.BlogSearchFeedUrl, TrendWord);
            BlogSearchListView.DataSourceID = BlogSearchDataSource.UniqueID;
            BlogSearchListView.DataBind();


            //show news from live com
            try
            {
                LiveNewsDataSource.DataFile = string.Format(LiveHelper.LiveNewsFeedUrl, TrendWord);
                LiveNewsListView.DataSourceID = LiveNewsDataSource.UniqueID;
                LiveNewsListView.DataBind();
            }
            catch (Exception)
            {

                throw;
            }


            //search results from live.com
            try
            {
                LiveSearchDataSource.DataFile = string.Format(LiveHelper.LiveSearchFeedUrl, TrendWord);
                LiveSearchListView.DataSourceID = LiveSearchDataSource.UniqueID;
                LiveSearchListView.DataBind();
            }
            catch (Exception)
            {

                //todo
            }


            //show videos from youtube
            LoadVideos(this.TrendWord);
            LoadPicasaImages();


        }

        //Set the title
        this.Title = GenerateTitle();
    }

    private void LoadPicasaImages()
    {
        AtomEntryCollection images = PicasaHelper.GetImagesByPhrase(this.TrendWord);
        PicasaImagesListView.DataSource = images;
        PicasaImagesListView.DataBind();
    }

    private void LoadVideos(string keyword)
    {
        try
        {
            string username = "seniordotnetdeveloper@gmail.com";
            string password = "dessi77&";
            string application = "buzzhour";
            string clientID = "ytapi-NikolayYordanov-buzzhour-673umn97-1";
            string developerKey = "AI39si65gkXT57qFsN8zVZiAMVRpySX9h_TVRKBS5F3bGrO0c06YuF6ISMhX2BQZyZp2MxMa_JOtcftvSeiA1kqIpzN2CulfYA";

            YouTubeService service = new YouTubeService(application, clientID, developerKey);
            service.setUserCredentials(username, password);

            YouTubeQuery query = new YouTubeQuery(YouTubeQuery.DefaultVideoUri);
            query.Query = keyword;
            query.NumberToRetrieve = 18;
            YouTubeFeed videoFeed = service.Query(query);
            VideosListView.DataSource = videoFeed.Entries;
            VideosListView.DataBind();
            if (videoFeed.Entries.Count > 0)
            {
                VideosListView.SelectedIndex = 0;
                VideosListView_SelectedIndexChanged(VideosListView, new EventArgs());
            }
        }
        catch (Exception)
        {

        }

    }

    private string GenerateTitle()
    {
        StringBuilder result = new StringBuilder();
        result.Append(this.TrendWord);
        result.Append(" - Latest ");
        Thread.CurrentThread.CurrentCulture = new System.Globalization.CultureInfo("en-us");
        //result.Append(DateTime.Now.ToLongDateString());
        result.Append(" News, Blogs, Pictures And Videos");
        string actualResult = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(result.ToString());
        return actualResult;
    }

    protected void VideosListView_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (VideosListView.Items[VideosListView.SelectedIndex].ItemType == ListViewItemType.DataItem)
        {

            ListViewDataItem data = VideosListView.Items[VideosListView.SelectedIndex] as ListViewDataItem;
            ImageButton VideoThumbNail = VideosListView.Items[VideosListView.SelectedIndex].FindControl("VideoThumbNail") as ImageButton;
            VideoPlayerSource.Text = ComplexStrings.YouTubePlayerNormalSize.Replace("MovieId", VideoThumbNail.DescriptionUrl);

        }

    }

    protected void PicasaImagesListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem dataItem = e.Item as ListViewDataItem;
            PicasaEntry picasaImage = dataItem.DataItem as PicasaEntry;
            ImageButton ImageThumbNail = e.Item.FindControl("ImageThumbNail") as ImageButton;
            ImageThumbNail.ImageUrl = picasaImage.Media.Thumbnails[2].Url;
            ImageThumbNail.AlternateText = picasaImage.Summary.Text;
            Label ImageTitle = e.Item.FindControl("ImageTitle") as Label;
            ImageTitle.Text = picasaImage.Summary.Text;

        }
    }

    protected void PicasaImagesListView_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
    {

    }

    protected void PicasaImagesListView_SelectedIndexChanged(object sender, EventArgs e)
    {

    }

    protected void VideosListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {
        if (e.Item.ItemType == ListViewItemType.DataItem)
        {
            ListViewDataItem data = e.Item as ListViewDataItem;
            YouTubeEntry entry = data.DataItem as YouTubeEntry;
            ImageButton VideoThumbNail = e.Item.FindControl("VideoThumbNail") as ImageButton;
            Label VideoTitle = e.Item.FindControl("VideoTitle") as Label;
            VideoTitle.Text = entry.Title.Text;
            VideoThumbNail.ImageUrl = entry.Media.Thumbnails[0].Url;
            try
            {
                VideoThumbNail.DescriptionUrl = entry.Media.VideoId.Value; 
            }
            catch (Exception)
            {

            }


        }
    }

    protected void VideosListView_SelectedIndexChanging(object sender, ListViewSelectEventArgs e)
    {
        if (VideosListView.Items[VideosListView.SelectedIndex].ItemType == ListViewItemType.DataItem)
        {
            VideosListView.SelectedIndex = e.NewSelectedIndex;

            e.Cancel = false;

        }
    }
    protected void GoogleNewsListView_ItemDataBound(object sender, ListViewItemEventArgs e)
    {

    }
    protected void GoogleNewsListView_ItemCreated(object sender, ListViewItemEventArgs e)
    {

    }
    protected void GoogleNewsListView_DataBound(object sender, EventArgs e)
    {
        if (GoogleNewsListView.Items != null && GoogleNewsListView.Items.Count > 0)
        {
            foreach (ListViewItem item in GoogleNewsListView.Items)
            {
                Label adsenseLabel = item.FindControl("AdsenseInlineLabel") as Label;
                adsenseLabel.Text = ComplexStrings.Adsense336x280;
                adsenseLabel.Visible = true;
            }
        }
    }

}
